<template lang="pug">
  div.upload-modal-button
    el-button(@click="dialogVisible = true") {{ buttonText }}
    el-dialog.center(:visible.sync="dialogVisible")
      p
        el-upload(
          action="undefined"
          :auto-upload="autoUpload"
          :on-change="handleChange"
          :on-remove="handleRemove"
          accept=".xlsx,.xls"
        )
          el-button(type="primary") 选择文件
            i.el-icon-upload.el-icon--right
          div(v-if="tip" slot="tip" class="el-upload__tip") {{ tip }}
      p(v-if="templateFileUrl")
        a(:href="templateFileUrl") 点击>下载模板
      span(slot="footer" class="dialog-footer")
        el-button(@click="dialogVisible = false") 取消
        el-button(@click="upload" type="primary") 确定
</template>
<script>
import { Message, MessageBox } from "element-ui";
export default {
    name: "UploadModalButton",
    props: {
        action: {
            type: String,
            required: true
        },
        field: {
            type: String,
            default: "file"
        },
        templateFileUrl: {
            type: String,
            default: ""
        },
        buttonText: {
            type: String,
            default: "上传"
        },
        tip: {
            type: String,
            default: ""
        },
        autoUpload: {
            type: Boolean,
            default: false
        }
    },
    data: () => ({
        dialogVisible: false,
        file: null
    }),
    methods: {
        handleChange(file) {
            this.file = file.raw;
        },
        handleRemove() {
            this.file = null;
        },
        upload() {
            if (!this.file) {
                Message("请选择文件！");
                return;
            }
            this.$store
                .dispatch(this.action, {
                    [this.field]: this.file
                })
                .then(() => {
                    this.dialogVisible = false;
                    this.$emit("ok");
                })
                .catch(err => {
                    MessageBox(err.message);
                });
        }
    }
};
</script>

<style lang="scss" scoped>
.upload-modal-button {
  display: inline-block;
  margin: 0 10px;
}
</style>
